/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package korekosystem.vista;

import java.awt.Point;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.*;
import javax.swing.JOptionPane;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import korekosystem.modelo.Cliente;
import korekosystem.modelo.Cobro;
import korekosystem.modelo.Detallexventa;
import korekosystem.modelo.Producto;
import korekosystem.modelo.Venta;
import korekosystem.DatePicker;
import korekosystem.ObservingTextField;
import net.coderazzi.filters.gui.TableFilterHeader;

/**
 *
 * @author groupweird
 */
public class ABMVenta extends javax.swing.JInternalFrame {

    @PersistenceContext
    EntityManager entityMgr;
    
    Venta venta;
    long total;
    int filaEditada;
    List<Detallexventa> detallexventaList;
    /**
     * Creates new form ABMVenta
     */
    public ABMVenta() {
        initComponents();
        filaEditada = -1;
        
        TableFilterHeader tablefilter = new TableFilterHeader(jTable1);
     this.addInternalFrameListener(new InternalFrameAdapter() {
            
            // Cierra el entityManager cuando se cierra
            // la ventana
            @Override
            public void internalFrameClosed(InternalFrameEvent ev) {
                if (entityMgr != null && entityMgr.isOpen()) {
                    entityMgr.close();
                }
            }
            // Se reescribe el evento cuando se abre la ventana
            // para que instancie el entityManager
            @Override
            public void internalFrameOpened(InternalFrameEvent ev) {
                ABMVenta estaVentana =
                        (ABMVenta) ev.getSource();
                try {
                    entityMgr = Persistence
                            .createEntityManagerFactory("KorekoSystemPU")
                            .createEntityManager();
                    estaVentana.llenarCBProducto();
                    estaVentana.llenarCBCliente();
                    estaVentana.limpiar2();
                    inicializarCampos();
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(estaVentana,
                            "Error al inciar el motor de persistencia\n [" +
                            e.getMessage() + "]");
                    estaVentana.dispose();
                }
            }
        });
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        numeroFacturaText = new javax.swing.JTextField();
        fechaText = new javax.swing.JFormattedTextField();
        jLabel7 = new javax.swing.JLabel();
        clienteComboBox = new javax.swing.JComboBox();
        guardarButton = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        productoComboBox = new javax.swing.JComboBox();
        cantidadText = new javax.swing.JFormattedTextField();
        precioUnitarioText = new javax.swing.JFormattedTextField();
        agregarButton = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        borrarButton = new javax.swing.JButton();
        totalLabel = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jPanel3 = new javax.swing.JPanel();
        cantidadText1 = new javax.swing.JFormattedTextField();
        diasText = new javax.swing.JFormattedTextField();
        jLabel9 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        jLabel12 = new javax.swing.JLabel();
        totalLabel1 = new javax.swing.JLabel();
        jLabel13 = new javax.swing.JLabel();
        jLabel14 = new javax.swing.JLabel();
        recargoText = new javax.swing.JFormattedTextField();
        contadoButton = new javax.swing.JRadioButton();
        CuotasButton = new javax.swing.JRadioButton();
        fechaCuotaButton = new javax.swing.JButton();
        fechaText1 = new korekosystem.ObservingTextField();

        setTitle("ABMVenta");

        jScrollPane1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jTable1.setAutoCreateRowSorter(true);
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "", "Producto", "Cantidad", "Precio Unitario", "Subtotal"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Boolean.class, java.lang.String.class, java.lang.Integer.class, java.lang.Long.class, java.lang.Long.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel1.setText("Nro. de Factura:");

        jLabel2.setText("Fecha:");

        try {
            fechaText.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        fechaText.setFocusLostBehavior(javax.swing.JFormattedTextField.PERSIST);

        jLabel7.setText("Cliente");

        clienteComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGap(33, 33, 33)
                .addComponent(jLabel7)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(clienteComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(numeroFacturaText, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(53, 53, 53)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(fechaText, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(clienteComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel7))
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(numeroFacturaText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel2)
                        .addComponent(fechaText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(21, Short.MAX_VALUE))
        );

        guardarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/guardar.png"))); // NOI18N
        guardarButton.setText("Guardar");
        guardarButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                guardarButtonMouseClicked(evt);
            }
        });

        jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jPanel2.setName(""); // NOI18N

        productoComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        try {
            cantidadText.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        cantidadText.setFocusLostBehavior(javax.swing.JFormattedTextField.PERSIST);

        try {
            precioUnitarioText.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("#########")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        precioUnitarioText.setFocusLostBehavior(javax.swing.JFormattedTextField.PERSIST);

        agregarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/guardar.png"))); // NOI18N
        agregarButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                agregarButtonMouseClicked(evt);
            }
        });
        agregarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                agregarButtonActionPerformed(evt);
            }
        });

        jLabel3.setText("Productos");

        jLabel4.setText("Cantidad");

        jLabel5.setText("Precio Unitario");

        borrarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/eliminar.png"))); // NOI18N
        borrarButton.setEnabled(false);
        borrarButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                borrarButtonMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(productoComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(29, 29, 29)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cantidadText, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(precioUnitarioText, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(agregarButton, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(borrarButton, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(agregarButton)
                    .addComponent(borrarButton)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(productoComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(cantidadText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(precioUnitarioText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel3)
                        .addComponent(jLabel4)
                        .addComponent(jLabel5)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        totalLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        totalLabel.setToolTipText("");
        totalLabel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        jLabel6.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel6.setText("TOTAL SIN RECARGO:");
        jLabel6.setToolTipText("");

        jPanel3.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jPanel3.setToolTipText("Cuotas");
        jPanel3.setName(""); // NOI18N

        cantidadText1.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0"))));
        cantidadText1.setFocusLostBehavior(javax.swing.JFormattedTextField.PERSIST);

        try {
            diasText.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        diasText.setFocusLostBehavior(javax.swing.JFormattedTextField.PERSIST);

        jLabel9.setText("Cantidad");

        jLabel10.setText("Cada");

        jLabel11.setText("dias");

        jLabel12.setText("Desde:");

        totalLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        totalLabel1.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        totalLabel1.setToolTipText("");
        totalLabel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        jLabel13.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel13.setText("TOTAL:");
        jLabel13.setToolTipText("");

        jLabel14.setText("% Recargo");

        try {
            recargoText.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        recargoText.setFocusLostBehavior(javax.swing.JFormattedTextField.PERSIST);
        recargoText.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                recargoTextKeyReleased(evt);
            }
        });

        contadoButton.setSelected(true);
        contadoButton.setText("Contado");
        contadoButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                contadoButtonMouseClicked(evt);
            }
        });

        CuotasButton.setText("Cuotas");
        CuotasButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                CuotasButtonMouseClicked(evt);
            }
        });

        fechaCuotaButton.setText("...");
        fechaCuotaButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                fechaCuotaButtonMouseClicked(evt);
            }
        });

        try {
            fechaText1.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(contadoButton)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(jLabel9)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(cantidadText1, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(CuotasButton)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGap(30, 30, 30)
                        .addComponent(jLabel10)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(diasText, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel11)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel12)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(fechaText1, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(fechaCuotaButton, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 26, Short.MAX_VALUE)
                        .addComponent(jLabel14)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(recargoText, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel13)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(totalLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(totalLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(contadoButton)
                            .addComponent(CuotasButton))
                        .addGap(13, 13, 13)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel9)
                            .addComponent(cantidadText1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel10)
                            .addComponent(diasText)
                            .addComponent(jLabel11)
                            .addComponent(jLabel12)
                            .addComponent(jLabel14)
                            .addComponent(recargoText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel13, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(fechaText1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(fechaCuotaButton))))
                .addGap(0, 119, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(jLabel6)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(totalLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(guardarButton, javax.swing.GroupLayout.Alignment.TRAILING)))
                    .addComponent(jPanel3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(12, 12, 12)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 185, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jLabel6)
                    .addComponent(totalLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(guardarButton)
                .addGap(48, 48, 48))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        // TODO add your handling code here:
        // esto sirve para que efectivamente tome en cuenta solo los
        // clicks en la primera columna (la columna de seleccion)
        Point p = evt.getPoint();
        if (jTable1.columnAtPoint(p) == 0){
            // Recorremos toda la tabla, buscando los seleccionados
            // guardamos el numero de elementos seleccionados
            TableModel tm = jTable1.getModel();
            int selectcount = 0;
            int selectindex = 0;
            for (int i=0; i < tm.getRowCount(); i++ ){
                if( (Boolean) tm.getValueAt(i, 0) == true){
                    selectcount++;
                    selectindex = i;
                }
            }

            //si hay una fila seleccionada...
            if(selectcount == 1){
                rellenarCampos(selectindex);
                filaEditada = selectindex;
                borrarButton.setEnabled(true);
                agregarButton.setEnabled(true);
                
            //si no hay nada seleccionado...
            }else if (selectcount == 0){
                limpiar();
                filaEditada = -1;
                agregarButton.setEnabled(true);
                borrarButton.setEnabled(false);
                
            //si hay mas de uno seleccionado...
            }else{
                limpiar();
                filaEditada = -1;
                borrarButton.setEnabled(true);
                agregarButton.setEnabled(false);
            }
        }

    }//GEN-LAST:event_jTable1MouseClicked

    private void guardarButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_guardarButtonMouseClicked
        // TODO add your handling code here:
        int confirmacionGuardado = 0;
        //Controles de campos vacíos factura y fecha de venta
        if(numeroFacturaText.getText() == null || numeroFacturaText.getText().trim().equals("")) {
            JOptionPane.showMessageDialog(this, "El número de Factura no puede ser nulo");
            numeroFacturaText.requestFocus();
            return;        
        } else if(fechaText.getText() == null || fechaText.getText().trim().equals("")) {
            JOptionPane.showMessageDialog(this, "La fecha no puede ser nula");
            fechaText.requestFocus();
            return;
        } else if(fechaText1.getText() == null || fechaText1.getText().trim().equals("")) {
            JOptionPane.showMessageDialog(this, "La fecha de cobro(s) no puede ser nula");
            fechaText1.requestFocus();
            return;    
            
        // Control de fechas válidas
        } else if (isFechaValida(fechaText.getText())== false){
            JOptionPane.showMessageDialog(this, "Fecha de venta inválida.");
            fechaText.requestFocus();
            return;
            
        } else if (isFechaValida(fechaText1.getText())== false){
            JOptionPane.showMessageDialog(this, "Fecha de cobro(s) inválida.");
            fechaText1.requestFocus();
            return;
        
        //Control de selección de un cliente    
        } else if((Cliente)clienteComboBox.getSelectedItem() == null){
            JOptionPane.showMessageDialog(this, "No seleccionó ningún cliente");
            clienteComboBox.requestFocus();
            return; 
           
        // Control de que exista por lo menos un detalle
        } else if(jTable1.getRowCount()<1){
            JOptionPane.showMessageDialog(this, "No existe ningún detalle.");
            jTable1.requestFocus();
            return;
      
        // Control de campo % recargo    
        } else if(recargoText.getText() == null || recargoText.getText().trim().equals("")){
            JOptionPane.showMessageDialog(this, "El campo 'Recargo' no puede estar vacio.");
            recargoText.requestFocus();
            return;
            
        // Controles de campos en caso de que sea a cuotas
        } else if (CuotasButton.isSelected()){
                if(cantidadText1.getText() == null || cantidadText1.getText().trim().equals("") || Integer.valueOf(cantidadText1.getText().trim())<2){
                        JOptionPane.showMessageDialog(this, "La cantidad de cuotas no es válida. La cantidad de cuotas debe ser mayor a 1.");
                         cantidadText1.requestFocus();
                        return;
                }
                if(diasText.getText() == null || diasText.getText().trim().equals("") || Integer.valueOf(diasText.getText().trim())<1){
                        JOptionPane.showMessageDialog(this, "La cantidad de dias de cobro de las cuotas no es válida.");
                         diasText.requestFocus();
                        return;
                }
        }
        
        confirmacionGuardado = JOptionPane.showConfirmDialog(this, "Confirmar guardado", "Advertencia", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
        if(confirmacionGuardado == 0){ 
        //Inicio de la transacción
            EntityTransaction tr = null;
            try {
                tr = entityMgr.getTransaction();
                tr.begin();
                // si el id de la bd es nulo el objeto no existe y se instancia
                if (venta == null) {
                    venta = new Venta();
                    venta.setNrofactura(Integer.valueOf(numeroFacturaText.getText().trim()));
                    venta.setCliente((Cliente)clienteComboBox.getSelectedItem());

                    SimpleDateFormat formato = new SimpleDateFormat("dd/MM/yyyy");
                    try {
                        venta.setFecha(formato.parse(fechaText.getText()));
                    } catch (ParseException ex) {
                        ex.printStackTrace();
                    }       
                    entityMgr.persist(venta);
                } 

                entityMgr.flush(); 

                try{
                    cargarDetalle(venta);
                    venta.setDetallexventaList(detallexventaList);
                    for (Detallexventa detalle : detallexventaList){
                        Producto p = detalle.getProducto();
                        p.setStock(p.getStock()-detalle.getCantidad());
                    }
                    entityMgr.merge(venta);

                }
                catch (Exception e) {
                    if (tr != null && tr.isActive() ) {
                        tr.rollback();
                    }
                    JOptionPane.showMessageDialog(this, "Error del sistema: [" +
                        e.getMessage() + "]");
                        e.printStackTrace();
                }
                try{
                    long totalGral = Long.valueOf(totalLabel1.getText());
                    venta.setTotal(totalGral);
                    //Si es al contado   
                    if (contadoButton.isSelected()){
                        Cobro cobro = new Cobro();
                        cobro.setCliente((Cliente)clienteComboBox.getSelectedItem());
                        cobro.setMonto(Long.valueOf(totalLabel1.getText()));
                        cobro.setVenta(venta);

                        // Se cobra en el momento
                        if (fechaText1.getText().equalsIgnoreCase(fechaText.getText())){                            
                            cobro.setPendiente(false);
                            SimpleDateFormat formato = new SimpleDateFormat("dd/MM/yyyy");
                            try {
                                cobro.setFecha(formato.parse(fechaText1.getText()));
                            } catch (ParseException ex) {
                                ex.printStackTrace();
                            }
                        // a cobrar en otra fecha
                        } else{
                            cobro.setPendiente(true);
                            SimpleDateFormat formato = new SimpleDateFormat("dd/MM/yyyy");
                            try {
                                cobro.setFecha(formato.parse(fechaText1.getText()));
                            } catch (ParseException ex) {
                                ex.printStackTrace();
                            }

                            Cliente clienteActual = (Cliente)clienteComboBox.getSelectedItem();
                            clienteActual.setSaldo(clienteActual.getSaldo()+totalGral);

                            entityMgr.merge(clienteActual);

                        }
                        entityMgr.persist(cobro);

                        // Caso: Existen cuotas   
                    } else {             

                        long cantidadCuotas = Long.valueOf(cantidadText1.getText());

                        for(int i=0; i<cantidadCuotas; i++){
                            Cobro cobro = new Cobro();
                            cobro.setCliente((Cliente)clienteComboBox.getSelectedItem());
                            cobro.setMonto(0);
                            cobro.setPendiente(true);
                            cobro.setFecha(controlFecha(i));
                            cobro.setVenta(venta);

                            entityMgr.persist(cobro);
                        }
                        Cliente clienteActual = (Cliente)clienteComboBox.getSelectedItem();
                        clienteActual.setSaldo(clienteActual.getSaldo()+totalGral);

                        entityMgr.merge(clienteActual);
                    }
                    tr.commit();

                }
                catch (Exception e) {
                    if (tr != null && tr.isActive() ) {
                        tr.rollback();
                    }
                    JOptionPane.showMessageDialog(this, "Error del sistema: [" +
                        e.getMessage() + "]");
                        e.printStackTrace();
                }

                JOptionPane.showMessageDialog(this, "Cambios guardados con exito!");

            }catch (Exception e) {
                if (tr != null && tr.isActive()) {
                    tr.rollback();
                }
                JOptionPane.showMessageDialog(this, "Error del sistema: [" +
                    e.getMessage() + "]");
                    e.printStackTrace();

            }finally{
                venta = null;
                total = 0;
                limpiar2();
                DefaultTableModel tm = ((DefaultTableModel)jTable1.getModel());
                tm.setRowCount(0);

                inicializarCampos();
            }
        } else if(confirmacionGuardado == 1){
        
        }
        
    }//GEN-LAST:event_guardarButtonMouseClicked

    private void agregarButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_agregarButtonMouseClicked
        // TODO add your handling code here:
        
        // Controles realizados sobre valores de campos a rellenar
        if(cantidadText.getText() == null || cantidadText.getText().trim().equals("") || Long.valueOf(cantidadText.getText().trim())<1 ){
            JOptionPane.showMessageDialog(this, "La cantidad no puede ser nula");
            cantidadText.requestFocus();
            return;
            
        } else if(precioUnitarioText.getText() == null || precioUnitarioText.getText().trim().equals("") || Long.valueOf(precioUnitarioText.getText().trim())<1) {
            JOptionPane.showMessageDialog(this, "El precio no puede ser nulo");
            precioUnitarioText.requestFocus();
            return;
        }
        
        if (productoComboBox.getSelectedIndex()== -1 ||
                productoComboBox.getSelectedItem().equals("")) {
            JOptionPane.showMessageDialog(this, "No se ha seleccionado ningún producto.");
            precioUnitarioText.requestFocus();
            return;
        }    
        // Control de cantidad a vender sobre Stock del producto
        if (Long.valueOf(cantidadText.getText().trim()) > ((Producto)productoComboBox.getSelectedItem()).getStock()){
            JOptionPane.showMessageDialog(this, "La cantidad supera el Stock del producto");
            cantidadText.requestFocus();
            return;
        }
        
        //Si se está editando y no agregando
        if(filaEditada != -1){
            Long subtotalAnterior = (Long.valueOf(jTable1.getModel().getValueAt(filaEditada, 4).toString()));
            total = total - subtotalAnterior;
        }
        
        
        //Rellena la tabla con los valores introducidos
        Vector vec = new Vector();
        vec.add(false);
        vec.add((Producto)productoComboBox.getSelectedItem());
        vec.add(Integer.valueOf(cantidadText.getText().trim()));
        vec.add(Long.valueOf(precioUnitarioText.getText().trim()));
        long subtotal = (Long.valueOf(precioUnitarioText.getText().trim())*Integer.valueOf(cantidadText.getText().trim()));
        vec.add(subtotal);
        total = total + subtotal;
      
       
        DefaultTableModel tm = ((DefaultTableModel)jTable1.getModel());
        //En caso de haber seleccionado una fila filaEditada adquiere el valor de la fila
        //Sino entonces significa que se agregará una nueva fila
        if(filaEditada != -1){
            tm.removeRow(filaEditada);
            tm.insertRow(filaEditada, vec);
            filaEditada = -1;
        }
        else {
            tm.addRow(vec);
        }
        
        limpiar();
        totalLabel.setText(String.valueOf(total));
        actualizarTotal();
      
    }//GEN-LAST:event_agregarButtonMouseClicked

    private void borrarButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_borrarButtonMouseClicked
        // TODO add your handling code here:
        //Recorre la tabla y elimina los seleccionados
        int contadorControlEdicion = 0;
        DefaultTableModel tm = ((DefaultTableModel)jTable1.getModel());

        for (int i=0; i < tm.getRowCount(); i++ ){
            if( (Boolean) tm.getValueAt(i, 0) == true){
                total = total - Long.valueOf(tm.getValueAt(i, 4).toString());
                totalLabel.setText(String.valueOf(total));
                tm.removeRow(i);
                i--;
                contadorControlEdicion++;
            }
        }
        
        //Si se selecciono uno solo volver a establecer a -1 la variable filaEditada 
        // luego de la eliminacion
        if (contadorControlEdicion == 1){
            filaEditada = -1;  
        }
        //Actualiza el total general con recargo tras la eliminacion
        // El subtotal ya se actualiza en el 'for' anterior
        actualizarTotal();
        limpiar();
        
    }//GEN-LAST:event_borrarButtonMouseClicked

    private void recargoTextKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_recargoTextKeyReleased
        // TODO add your handling code here:
       actualizarTotal();
       
    }//GEN-LAST:event_recargoTextKeyReleased

    private void contadoButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_contadoButtonMouseClicked
        // TODO add your handling code here:
        cantidadText1.setEnabled(false);
        diasText.setEnabled(false);
        CuotasButton.setSelected(false);
        contadoButton.setSelected(true);
        
    }//GEN-LAST:event_contadoButtonMouseClicked

    private void CuotasButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_CuotasButtonMouseClicked
        // TODO add your handling code here:
        cantidadText1.setEnabled(true);
        diasText.setEnabled(true);
        contadoButton.setSelected(false);
        CuotasButton.setSelected(true);

    }//GEN-LAST:event_CuotasButtonMouseClicked

    private void agregarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_agregarButtonActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_agregarButtonActionPerformed

    private void fechaCuotaButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_fechaCuotaButtonMouseClicked
        //En este lugar se crea el calendario que aparece al hacer clic en el 
        //botón fechaButton
        //String lang = null;
        //lang = "PY";
        final Locale locale = Locale.getDefault();
        //final Locale locale = getLocale(lang);
        DatePicker dp = new DatePicker(fechaText1, locale);
        //previous selected date
        Date selectedDate = dp.parseDate(fechaText1.getText());
        dp.setSelectedDate(selectedDate);
        dp.start(fechaText1);
    }//GEN-LAST:event_fechaCuotaButtonMouseClicked

    //Método para hallar el estilo de fecha correspondiente a cada país
    //Sin utilizar por el momento
    private Locale getLocale(String loc){
        
        if(loc != null && loc.length() > 0){
            return new Locale("es",loc);
        }
        else{
            return Locale.US;
        }
    }
    
    public void actualizarTotal(){
        long subtotal = totalLabel.getText().isEmpty()? 0:( Long.valueOf(totalLabel.getText()) );
        float recargo =  recargoText.getText().trim().equals("") ? 0:( Float.valueOf(recargoText.getText().trim()) );
        recargo = recargo / 100;
        
        Long totGral = (subtotal + (long)(subtotal * recargo));
        totalLabel1.setText(String.valueOf( (Long) totGral ));
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JRadioButton CuotasButton;
    private javax.swing.JButton agregarButton;
    private javax.swing.JButton borrarButton;
    private javax.swing.JFormattedTextField cantidadText;
    private javax.swing.JFormattedTextField cantidadText1;
    private javax.swing.JComboBox clienteComboBox;
    private javax.swing.JRadioButton contadoButton;
    private javax.swing.JFormattedTextField diasText;
    private javax.swing.JButton fechaCuotaButton;
    private javax.swing.JFormattedTextField fechaText;
    private korekosystem.ObservingTextField fechaText1;
    private javax.swing.JButton guardarButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField numeroFacturaText;
    private javax.swing.JFormattedTextField precioUnitarioText;
    private javax.swing.JComboBox productoComboBox;
    private javax.swing.JFormattedTextField recargoText;
    private javax.swing.JLabel totalLabel;
    private javax.swing.JLabel totalLabel1;
    // End of variables declaration//GEN-END:variables

private void llenarCBProducto() {

    productoComboBox.removeAllItems();
    
    if ( entityMgr.isOpen()) {
                    try {
                        javax.persistence.Query q = entityMgr.createNamedQuery("Producto.findAll");
                        List<Producto> result = q.getResultList();
                        
                        for (Producto p: result){
                        productoComboBox.addItem(p);
                        }
                    }
                    catch (NoResultException  ignorada) {}
                    catch (Exception e) {
                        JOptionPane.showMessageDialog(this, "Error del sistema: [" +
                                e.getMessage() + "]");
                        e.printStackTrace();
                    }     
     }
}

private void llenarCBCliente() {

    clienteComboBox.removeAllItems();
    
    if ( entityMgr.isOpen()) {
                    try {
                        javax.persistence.Query q = entityMgr.createNamedQuery("Cliente.findByActivo");
                        List<Cliente> result = q.getResultList();
                        
                        for (Cliente c: result){
                        clienteComboBox.addItem(c);
                        }
                    }
                    catch (NoResultException  ignorada) {}
                    catch (Exception e) {
                        JOptionPane.showMessageDialog(this, "Error del sistema: [" +
                                e.getMessage() + "]");
                        e.printStackTrace();
                    }     
     }
}

private void rellenarCampos(int i){
    DefaultTableModel tm = ((DefaultTableModel)jTable1.getModel());
    productoComboBox.setSelectedItem((Producto)tm.getValueAt(i, 1));
    cantidadText.setText(tm.getValueAt(i, 2).toString());
    precioUnitarioText.setValue(tm.getValueAt(i, 3).toString()); 
}

private void limpiar(){
    precioUnitarioText.setText("");
    cantidadText.setText("");
    productoComboBox.setSelectedIndex(-1);
    agregarButton.setEnabled(true);
    borrarButton.setEnabled(false);
}

private void limpiar2(){
    cantidadText1.setText("");
    recargoText.setText("");
    diasText.setText("");
    totalLabel.setText("");
    totalLabel1.setText("");
    clienteComboBox.setSelectedIndex(-1);
    numeroFacturaText.setText("");
    limpiar();
}

private void cargarDetalle (Venta venta){
    TableModel tm = jTable1.getModel();
    detallexventaList = new ArrayList<Detallexventa>();
    
    for(int i=0;i<tm.getRowCount();i++){
        Detallexventa detalle = new Detallexventa();
        detalle.setCantidad(Integer.valueOf(tm.getValueAt(i, 2).toString()));
        detalle.setSubtotal(Long.valueOf(tm.getValueAt(i, 4).toString()));
        detalle.setProducto((Producto)tm.getValueAt(i,1));
        detalle.setVenta(venta);
     
        detallexventaList.add(detalle);
     }
}

private static boolean isFechaValida(String fechax) {
  try {
      SimpleDateFormat formatoFecha = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
      formatoFecha.setLenient(false);
      formatoFecha.parse(fechax);
  } catch (ParseException e) {
      return false;
  }
  return true;
}

private Date controlFecha(int i){
    Calendar cal= new GregorianCalendar();
    SimpleDateFormat formato = new SimpleDateFormat("dd/MM/yyyy");
    Date fech= null;
    try {
         if (fechaText1.getText() == null || fechaText1.getText().trim().equals("") || fechaText1.getValue() == null ){
            //cal.setTimeInMillis(formato.parse(fechaText.getText()).getTime());
        } else {
            cal.setTimeInMillis(formato.parse(fechaText1.getText()).getTime());
        }
        cal.add(Calendar.DATE,Integer.valueOf(diasText.getText().trim())*i);
        fech = new Date (cal.getTimeInMillis());
    }catch (ParseException ex) {
        ex.printStackTrace();
    }
    return fech;
}

private String getFechaActual(){
   SimpleDateFormat formato = new SimpleDateFormat("dd/MM/yyyy");
   return (String)formato.format(new Date());  
}

private void inicializarCampos (){

    fechaText.setValue(getFechaActual());
    fechaText1.setValue(getFechaActual());
    
    cantidadText1.setEnabled(false);
    diasText.setEnabled(false);
    contadoButton.setSelected(true);
    CuotasButton.setSelected(false);
   
}

}
